<?php


namespace App\HttpController\Home\Fanmh;


use App\Model\Fanmh\GoodModel;
use App\Model\UserModel;
use EasySwoole\Validate\Validate;

class GoodController extends \App\HttpController\Base
{

    //参数输入校验
    public function validateRule(string $action): ?Validate
    {
        $g = new Validate();
        switch ($action) {
            case "getGoodsInfo":
                $g->addColumn("good_id", "商品id")->required("参数不能缺少")->integer("参数必须是整型");
                break;

            case "updateGoodInfo":
            case "insertGoodInfo":
                $g->addColumn("goodName", "商品名")->required("商品名不能为空");
                $g->addColumn("goodPrice", "商品价格")->required("商品价格不能为空")->float("商品价格只能是数字");
                break;

        }
        return $g;
    }

    //
    public function getGoodsInfo()
    {
        //接收前端参数
        $params = $this->paramData;
        //"good_name"
        //调用商品模型-查询商品数据
        $goodsInfo = GoodModel::create()->getGoodsInfo($params["good_id"]);
        //遍历查到的数据
        $result = [];
        foreach ($goodsInfo as $key => $value) {
            $result[$key]["id"] = $value["good_id"];
            $result[$key]["name"] = $value["good_name"];
            $result[$key]["price"] = $value["good_price"];
        }
        //返回数据给前端
        return $this->returnMsg($result);
    }
    public function insertGoodInfo()
    {
        $params = $this->paramData;
        $insert_data =[
            "good_name"=>$params["goodName"],
            "good_price"=>$params["goodPrice"]
        ];
        $goodInfo = GoodModel::create()->insertGoodInfo($insert_data);
        return $this->returnMsg([$goodInfo]);
    }

    //修改商品价格
    public function updateGoodInfo(){
        $params = $this->paramData;
        $goodName = $params["goodName"];
        $goodPrice = $params["goodPrice"];
        $good_info = GoodModel::create()->updateGoodInfo($goodName,$goodPrice);
        if ($good_info <= 0) {
            return $this->returnMsg([], 50000, "价格修改失败");
        }
        return $this->returnMsg([], 20000, "修改成功");
    }

    //删除商品
    public function deleteGoodInfo(){
        $params = $this->paramData;
        $goodName = $params["goodName"];
        $good_info = UserModel::create()->destroy(["goodName",$goodName]);
        return $this->returnMsg([],2000,"商品删除成功");
    }


}

?>